<template>
  <div class="student-assignment-management">
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="24" type="flex" align="middle">
            <a-col>
              <a-form-item label="作业ID">
                <a-input 
                  v-model="queryParams.assignmentId" 
                  placeholder="请输入作业ID" 
                  allowClear
                  @pressEnter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="学生ID">
                <a-input 
                  v-model="queryParams.studentId" 
                  placeholder="请输入学生ID" 
                  allowClear
                  @pressEnter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col>
              <a-form-item label="状态">
                <a-select 
                  v-model="queryParams.status" 
                  placeholder="请选择状态" 
                  allowClear
                >
                  <a-select-option value="wait">待提交</a-select-option>
                  <a-select-option value="pending">批改中</a-select-option>
                  <a-select-option value="completed">已完成</a-select-option>
                  <a-select-option value="error">错误</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col flex="auto">
              <a-form-item>
                <a-space>
                  <a-button type="primary" @click="handleSearch">
                    <template #icon><search-outlined /></template>
                    查询
                  </a-button>
                  <a-button @click="handleReset">
                    <template #icon><reload-outlined /></template>
                    重置
                  </a-button>
                </a-space>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!-- 学生作业表格 -->
      <a-table
        :columns="columns"
        :data-source="studentAssignmentList"
        :pagination="pagination"
        :loading="loading"
        rowKey="id"
        @change="handleTableChange"
      >
        <!-- 状态列自定义渲染 -->
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          
          <!-- 操作列 -->
          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="handleViewDetails(record)">查看详情</a>
              <a-divider type="vertical" />
              
              <!-- 待提交状态并且角色为学生 - 允许提交作业 -->
              <a v-if="record.status === 'wait' && isStudent" @click="handleSubmitAssignment(record)">提交作业</a>
              
              <!-- 待批改状态并且角色为教师 - 允许批改作业 -->
              <a v-if="record.status === 'pending' && isTeacher" @click="handleGradeAssignment(record)">批改作业</a>
              
              <a-divider type="vertical" />
              <a-popconfirm
                v-if="isTeacher"
                title="确定要删除此学生作业吗?"
                ok-text="是"
                cancel-text="否"
                @confirm="handleDelete(record)"
              >
                <a>删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 提交作业对话框 -->
    <a-modal
      :visible="submissionModalVisible"
      @update:visible="submissionModalVisible = $event"
      title="提交作业"
      :footer="null"
      @cancel="handleSubmissionCancel"
      width="600px"
    >
      <div v-if="currentAssignment">
        <p><strong>作业：</strong>{{ currentAssignment.assignmentTitle }}</p>
        <p v-if="currentAssignment.studentName"><strong>学生：</strong>{{ currentAssignment.studentName }}</p>
        <a-divider />
        
        <a-upload
          name="file"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :customRequest="customRequest"
          @change="handleUploadChange"
          :showUploadList="{
            showPreviewIcon: true,
            showRemoveIcon: true,
            showDownloadIcon: false
          }"
        >
          <a-button type="primary" :loading="uploadLoading">
            <template #icon><upload-outlined /></template>
            选择文件并上传
          </a-button>
          <div style="margin-top: 8px; color: #999">
            请上传Word格式(.doc, .docx)的文件，大小不超过10MB
          </div>
        </a-upload>
        
        <div style="margin-top: 20px;">
          <a-alert type="info" show-icon>
            <template #message>提交须知</template>
            <template #description>
              <p>1. 提交后将自动开始AI批改，请耐心等待</p>
              <p>2. 批改完成后可在详情页查看结果</p>
              <p>3. 提交后状态将更新为"批改中"</p>
            </template>
          </a-alert>
        </div>
      </div>
    </a-modal>

    <!-- 批改作业对话框 -->
    <a-modal
      :visible="gradingModalVisible"
      @update:visible="gradingModalVisible = $event"
      title="🤖 AI智能批改"
      :footer="null"
      @cancel="handleGradingCancel"
      width="950px"
      :destroyOnClose="true"
      :maskClosable="false"
      class="ai-grading-modal"
    >
      <div v-if="currentGradingAssignment" class="ai-grading-container">
        <!-- 作业信息 -->
        <div class="assignment-info">
          <a-descriptions :column="2" size="small" bordered>
            <a-descriptions-item label="📚 作业">{{ currentGradingAssignment.assignmentTitle }}</a-descriptions-item>
            <a-descriptions-item label="👤 学生">{{ currentGradingAssignment.studentName }}</a-descriptions-item>
          </a-descriptions>
        </div>
        
        <!-- 批改内容区域 -->
        <div class="grading-content-wrapper">
          <!-- 思考区域 -->
          <div v-if="thinkingContent.content || thinkingContent.isActive" class="thinking-section">
            <div class="thinking-header-line">
              <div class="thinking-title-group">
                <span class="thinking-icon">
                  <a-spin v-if="thinkingContent.isActive" size="small" />
                  <span v-else>🧠</span>
                </span>
                <span class="thinking-text">
                  {{ thinkingContent.isActive ? 'AI正在深度思考中...' : 'AI思考过程' }}
                </span>
                <span class="thinking-timer">
                  {{ formatThinkingTime(thinkingContent.duration) }}
                </span>
              </div>
              <a-button 
                type="link" 
                size="small" 
                v-if="!thinkingContent.isActive && thinkingContent.content"
                @click="toggleThinkingCollapse"
                class="collapse-btn"
              >
                {{ thinkingContent.collapsed ? '展开' : '收起' }}
                <DownOutlined v-if="thinkingContent.collapsed" />
                <UpOutlined v-else />
              </a-button>
            </div>
            
            <div 
              v-if="!thinkingContent.collapsed" 
              class="thinking-content"
              :class="{ 'thinking-active': thinkingContent.isActive }"
            >
              <div class="thinking-text-content">
                {{ cleanTextContent(thinkingContent.content) || '正在分析作业内容，思考批改要点...' }}
                <span v-if="thinkingContent.isActive" class="thinking-dots">
                  <span>.</span><span>.</span><span>.</span>
                </span>
              </div>
            </div>
          </div>
          
          <!-- 批改结果区域 -->
          <div v-if="gradingContent.content || gradingContent.isActive" class="grading-section">
            <div class="grading-header-line">
              <div class="grading-title-group">
                <span class="grading-icon">
                  <a-spin v-if="gradingContent.isActive" size="small" />
                  <span v-else>📝</span>
                </span>
                <span class="grading-text">
                  {{ gradingContent.isActive ? 'AI正在生成批改结果...' : '批改结果' }}
                </span>
              </div>
            </div>
            
            <div class="grading-content">
              <!-- 请求进行中 - 显示简洁的加载状态 -->
              <div v-if="gradingContent.isActive && !gradingContent.tempContent" class="grading-loading-state">
                <div class="loading-indicator">
                  <a-spin size="large" />
                  <p>AI正在智能分析中，请耐心等待...</p>
                </div>
              </div>
              
              <!-- 流式显示批改结果（实时更新） -->
              <div v-else-if="gradingContent.tempContent || gradingContent.content" class="text-display">
                <div class="grading-text-content grading-result-bold" :class="{ 'streaming': gradingContent.isActive }">
                  {{ cleanTextContent(gradingContent.tempContent || gradingContent.content) }}
                  <span v-if="gradingContent.isActive" class="grading-cursor">
                    <span>|</span>
                  </span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-if="!thinkingContent.content && !gradingContent.content && !gradingLoading" class="empty-state">
            <a-empty description="暂无批改内容">
              <template #image>
                <div class="empty-icon">🤖</div>
              </template>
            </a-empty>
          </div>
        </div>
        
        <!-- 操作提示 -->
        <div class="grading-tips">
          <a-alert 
            type="info" 
            show-icon 
            :message="gradingLoading ? 'AI正在智能分析中' : '批改完成'"
          >
            <template #description>
              {{ gradingLoading ? 
                'AI正在仔细分析学生作业，请耐心等待...' : 
                '批改已完成，您可以查看思考过程和批改结果'
              }}
            </template>
          </a-alert>
        </div>
        
        <!-- 批改完成后的操作按钮 -->
        <div v-if="gradingContent.isCompleted && !gradingLoading" class="grading-actions">
          <a-space>
            <a-button 
              type="primary" 
              @click="handleSubmitGrading"
              :loading="submitGradingLoading"
            >
              提交作业批改
            </a-button>
            <a-button 
              @click="handleReGrade"
              :loading="gradingLoading"
            >
              重新批改
            </a-button>
          </a-space>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { 
  deleteStudentAssignment,
  updateStudentAssignment,
  gradeStudentAssignment
} from '@/api/student'
import { uploadFile } from '@/api/assignment'
import request from '@/utils/request'
import { debounce } from 'lodash-es'
import { 
  SearchOutlined,
  ReloadOutlined,
  UploadOutlined,
  DownOutlined,
  UpOutlined
} from '@ant-design/icons-vue'

// 定义类型接口
interface StudentAssignment {
  id?: number | string
  assignmentId: number | string
  assignmentTitle?: string
  studentId: number | string
  studentName?: string
  content?: string
  fileUrl?: string
  filePath?: string
  status: string
  gradingResultId?: number | string
  createTime?: string
  updateTime?: string
  submitTime?: string
}

interface StudentAssignmentListParams {
  page: number
  pageSize: number
  assignmentId?: number | string
  studentId?: number | string
  status?: string
}

// 思考内容类型
interface ThinkingContent {
  content: string
  isActive: boolean
  collapsed: boolean
  startTime: number
  endTime?: number
  duration: number
}

// 批改内容类型
interface GradingContent {
  content: string           // 最终显示的内容
  tempContent: string      // 流式过程中的临时内容
  isActive: boolean        // 是否正在请求中
  isCompleted: boolean     // 是否已完成
}

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: '5%',
  },
  {
    title: '作业标题',
    dataIndex: 'assignmentTitle',
    width: '20%',
    ellipsis: true,
  },
  {
    title: '学生姓名',
    dataIndex: 'studentName',
    width: '10%',
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '10%',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '15%',
  }
]

// 查询参数
const queryParams = reactive<StudentAssignmentListParams>({
  page: 1,
  pageSize: 10,
  assignmentId: undefined,
  studentId: undefined,
  status: undefined
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

// 状态变量
const loading = ref<boolean>(false)
const studentAssignmentList = ref<StudentAssignment[]>([])
const submitGradingLoading = ref<boolean>(false)
const gradingResult = ref<string>('')

const router = useRouter()
const userStore = useUserStore()

// 获取用户角色信息
const userInfo = computed(() => userStore.userInfo)
const isTeacher = computed(() => userInfo.value?.role === 'teacher' || userInfo.value?.role === 'admin')
const isStudent = computed(() => userInfo.value?.role === 'student')

/**
 * 获取学生作业列表数据
 * 使用重试机制确保API响应超时时自动重试
 */
const fetchStudentAssignmentList = async () => {
  const startTime = Date.now()
  try {
    loading.value = true
    // 使用重试机制调用API
    const res = await request.retry({
      url: '/studentAssignments/page',
      method: 'post',
      data: queryParams
    }, {
      count: 3, // 最多重试3次
      delay: 1000 // 每次重试间隔1秒
    })
    
    if (res.code === 200 && res.data) {
      studentAssignmentList.value = res.data.result
      pagination.total = res.data.total
      pagination.current = queryParams.page
      
      // 如果加载时间超过1.5秒，显示提示
      if (Date.now() - startTime > 1500) {
        message.info('数据加载完成')
      }
    } else {
      message.error(res.message || '获取学生作业列表失败')
    }
  } catch (error) {
    console.error('获取学生作业列表失败', error)
    message.error('获取学生作业列表失败')
  } finally {
    loading.value = false
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case "pending":
      return '待批改'
    case 'completed':
      return '已完成'
    case 'error':
      return '错误'
    case 'wait':
      return '待提交'
    default:
      return '未知状态'
  }
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  switch (status) {
    case "pending":
      return 'default'
    case 'completed':
      return 'processing'
    case 'error':
      return 'error'
    case 'wait':
      return 'warning'
    default:
      return 'default'
  }
}

// 查询按钮点击事件
const handleSearch = debounce(() => {
  queryParams.page = 1
  fetchStudentAssignmentList()
}, 500)

// 重置按钮点击事件
const handleReset = () => {
  queryParams.assignmentId = undefined
  queryParams.studentId = undefined
  queryParams.status = undefined
  queryParams.page = 1
  fetchStudentAssignmentList()
}

// 表格变化事件
const handleTableChange = (pag: any, _filters: any, _sorter: any) => {
  // 同步更新分页参数
  queryParams.page = pag.current
  queryParams.pageSize = pag.pageSize
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  
  fetchStudentAssignmentList()
}

// 查看详情
const handleViewDetails = (record: StudentAssignment) => {
  if (!record.id) {
    message.error('记录ID不存在')
    return
  }
  
  // 跳转到详情页面
  router.push(`/student/detail/${record.id}`)
}

// 删除按钮点击事件
const handleDelete = async (record: StudentAssignment) => {
  if (!record.id) {
    message.error('记录ID不存在')
    return
  }
  
  try {
    const res = await deleteStudentAssignment(record.id)
    if (res.code === 200) {
      message.success('删除成功')
      fetchStudentAssignmentList()
    } else {
      message.error(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除学生作业失败', error)
    message.error('删除学生作业失败')
  }
}

// 提交作业对话框
const submissionModalVisible = ref<boolean>(false)
const currentAssignment = ref<StudentAssignment | null>(null)
const uploadLoading = ref<boolean>(false)
const fileList = ref<any[]>([])

// 批改作业对话框
const gradingModalVisible = ref<boolean>(false)
const currentGradingAssignment = ref<StudentAssignment | null>(null)
const gradingLoading = ref<boolean>(false)
const streamResponse = ref<string>('')

// 思考和批改内容状态
const thinkingContent = reactive<ThinkingContent>({
  content: '',
  isActive: false,
  collapsed: false,
  startTime: 0,
  endTime: undefined,
  duration: 0
})

const gradingContent = reactive<GradingContent>({
  content: '',
  tempContent: '',
  isActive: false,
  isCompleted: false
})

// 计时器相关
let thinkingTimer: number | null = null

// 格式化思考时间
const formatThinkingTime = (duration: number): string => {
  if (duration === 0) return ''
  const seconds = Math.floor(duration / 1000)
  if (seconds < 60) {
    return `已思考 ${seconds}秒`
  } else {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `已思考 ${minutes}分${remainingSeconds}秒`
  }
}

// 切换思考内容折叠状态
const toggleThinkingCollapse = () => {
  thinkingContent.collapsed = !thinkingContent.collapsed
}

// 开始思考计时
const startThinkingTimer = () => {
  thinkingContent.startTime = Date.now()
  thinkingContent.isActive = true
  thinkingContent.duration = 0
  
  thinkingTimer = window.setInterval(() => {
    thinkingContent.duration = Date.now() - thinkingContent.startTime
  }, 100)
}

// 结束思考计时
const stopThinkingTimer = () => {
  if (thinkingTimer) {
    clearInterval(thinkingTimer)
    thinkingTimer = null
  }
  thinkingContent.isActive = false
  thinkingContent.endTime = Date.now()
}

// 解析流式响应内容
const parseStreamContent = (chunk: string) => {
  // 移除 "data:" 前缀
  const cleanChunk = chunk.replace(/^data:\s*/gm, '')
  
  // 按行分割并处理
  const lines = cleanChunk.split('\n').filter(line => line.trim())
  
  for (const line of lines) {
    if (line.includes('[思考]')) {
      // 提取思考内容
      const thinkingMatch = line.match(/\[思考\]\s*(.*)/)
      if (thinkingMatch) {
        if (!thinkingContent.isActive && !thinkingContent.content) {
          startThinkingTimer()
        }
        thinkingContent.content += thinkingMatch[1] + '\n'
      }
    } else if (line.includes('[批改]')) {
      // 思考阶段结束，开始批改
      if (thinkingContent.isActive) {
        stopThinkingTimer()
      }
      
      // 提取批改内容 - 先累积到临时内容
      const gradingMatch = line.match(/\[批改\]\s*(.*)/)
      if (gradingMatch) {
        if (!gradingContent.isActive) {
          gradingContent.isActive = true
        }
        gradingContent.tempContent += gradingMatch[1] + '\n'
      }
    } else {
      // 普通内容，判断当前应该添加到哪个区域
      if (thinkingContent.isActive) {
        thinkingContent.content += line + '\n'
      } else if (gradingContent.isActive) {
        gradingContent.tempContent += line + '\n'
      }
    }
  }
}

// 重置内容状态
const resetContentState = () => {
  // 重置思考内容
  thinkingContent.content = ''
  thinkingContent.isActive = false
  thinkingContent.collapsed = false
  thinkingContent.startTime = 0
  thinkingContent.endTime = undefined
  thinkingContent.duration = 0
  
  // 重置批改内容
  gradingContent.content = ''
  gradingContent.tempContent = ''
  gradingContent.isActive = false
  gradingContent.isCompleted = false
  
  // 重置其他状态
  gradingResult.value = ''
  submitGradingLoading.value = false
  
  // 清除计时器
  if (thinkingTimer) {
    clearInterval(thinkingTimer)
    thinkingTimer = null
  }
}

// 提交作业
const handleSubmitAssignment = (record: StudentAssignment) => {
  currentAssignment.value = record
  submissionModalVisible.value = true
  fileList.value = []
}

// 文件上传前检查
const beforeUpload = (file: File) => {
  // 检查文件类型
  const isDocOrDocx = 
    file.type === 'application/msword' || 
    file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
    /\.(doc|docx)$/i.test(file.name)
  
  if (!isDocOrDocx) {
    message.error('只能上传Word文档!')
    return false
  }
  
  // 检查文件大小
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!')
    return false
  }
  
  return isDocOrDocx && isLt10M
}

// 文件上传变化处理
const handleUploadChange = (info: any) => {
  if (info.file.status === 'uploading') {
    uploadLoading.value = true
    return
  }
  
  if (info.file.status === 'done') {
    uploadLoading.value = false
    if (info.file.response && info.file.response.code === 200) {
      message.success('文件上传成功')
      // 关闭对话框并刷新列表
      submissionModalVisible.value = false
      fetchStudentAssignmentList()
    } else {
      message.error(info.file.response?.message || '上传失败，请重试')
    }
  } else if (info.file.status === 'error') {
    uploadLoading.value = false
    message.error('上传失败，请重试')
  }
  
  fileList.value = [...info.fileList].slice(-1) // 只保留最新上传的文件
}

/**
 * 文件上传的自定义请求
 * 先上传文件获取URL，再更新学生作业状态
 * @param options 上传选项
 */
const customRequest = async (options: any) => {
  const { file, onSuccess, onError } = options
  
  if (!currentAssignment.value?.id) {
    onError(new Error('作业ID不存在'))
    return
  }
  
  try {
    // 开始计时，用于估算完成时间
    const startTime = Date.now()
    message.loading({ content: '文件上传中...', key: 'fileUpload', duration: 0 })
    
    // 使用uploadFile接口上传文件
    const uploadRes = await uploadFile(file)
    
    if (uploadRes.code !== 200 || !uploadRes.data) {
      message.error({ content: uploadRes.message || '文件上传失败', key: 'fileUpload' })
      onError(new Error(uploadRes.message || '文件上传失败'))
      return
    }
    
    // 获取文件URL
    const fileUrl = typeof uploadRes.data === 'string' 
      ? uploadRes.data 
      : uploadRes.data.url
    
    // 使用updateStudentAssignment接口更新学生作业信息，将文件关联到作业
    const updateData: StudentAssignment = {
      id: currentAssignment.value.id,
      assignmentId: currentAssignment.value.assignmentId,
      studentId: currentAssignment.value.studentId,
      filePath: fileUrl,
      status: 'pending'
    }
    
    const updateRes = await updateStudentAssignment(updateData)
    
    if (updateRes.code === 200) {
      // 计算上传耗时
      const uploadTime = Date.now() - startTime
      message.success({ 
        content: `提交成功！耗时 ${(uploadTime/1000).toFixed(1)}秒，正在进行AI批改`, 
        key: 'fileUpload' 
      })
      onSuccess(updateRes)
      
      // 延迟关闭对话框并刷新列表，让用户有时间看到成功消息
      setTimeout(() => {
        submissionModalVisible.value = false
        fetchStudentAssignmentList()
      }, 1500)
    } else {
      message.error({ content: updateRes.message || '提交作业失败', key: 'fileUpload' })
      onError(new Error(updateRes.message || '提交作业失败'))
    }
  } catch (error) {
    console.error('提交作业失败', error)
    message.error({ content: '提交作业失败，请重试', key: 'fileUpload' })
    onError(error)
  }
}

// 提交作业对话框取消
const handleSubmissionCancel = () => {
  submissionModalVisible.value = false
  fileList.value = []
  currentAssignment.value = null
}

// 批改作业
const handleGradeAssignment = (record: StudentAssignment) => {
  if (!record.id) {
    message.error('记录ID不存在')
    return
  }
  
  // 重置状态
  resetContentState()
  
  currentGradingAssignment.value = record
  gradingModalVisible.value = true
  streamResponse.value = ''
  gradingLoading.value = true
  
  // 调用批改接口
  callGradingAPI(record.id)
}

// 调用批改API
const callGradingAPI = async (assignmentId: number | string) => {
  try {
    await gradeStudentAssignment(
      assignmentId,
      // onChunk - 处理流式响应片段
      (chunk: string) => {
        streamResponse.value += chunk
        // 解析内容到思考和批改区域的临时内容
        parseStreamContent(chunk)
      },
      // onComplete - 批改完成
      () => {
        gradingLoading.value = false
        // 确保思考计时器停止
        if (thinkingContent.isActive) {
          stopThinkingTimer()
        }
        // 将临时内容转为正式内容，设置完成状态
        gradingContent.content = gradingContent.tempContent
        gradingContent.isActive = false
        gradingContent.isCompleted = true
        
        // 保存完整的批改结果（思考过程 + 批改内容拼接）
        const thinkingSection = thinkingContent.content ? `【AI思考过程】\n\n${thinkingContent.content}\n\n` : ''
        const gradingSection = `【批改结果】\n\n${gradingContent.content}`
        gradingResult.value = thinkingSection + gradingSection
        
        message.success('批改完成')
        // 刷新列表
        fetchStudentAssignmentList()
      },
      // onError - 错误处理
      () => {
        gradingLoading.value = false
        // 停止所有计时器
        if (thinkingContent.isActive) {
          stopThinkingTimer()
        }
        gradingContent.isActive = false
        gradingContent.isCompleted = false
        message.error('批改作业失败，请重试')
      }
    )
  } catch {
    gradingLoading.value = false
    // 停止所有计时器
    if (thinkingContent.isActive) {
      stopThinkingTimer()
    }
    gradingContent.isActive = false
    gradingContent.isCompleted = false
    message.error('批改作业失败，请重试')
  }
}

// 批改作业对话框取消
const handleGradingCancel = () => {
  gradingModalVisible.value = false
  currentGradingAssignment.value = null
  streamResponse.value = ''
  gradingLoading.value = false
  // 重置所有状态
  resetContentState()
}

// 页面加载时获取数据
onMounted(() => {
  fetchStudentAssignmentList()
})

// 新增方法 - 优化文本内容，处理间隙问题
const cleanTextContent = (content: string): string => {
  if (!content) return ''
  return content
    .replace(/\s+/g, ' ')           // 多个空格合并为一个
    .replace(/\n\s*\n/g, '\n')      // 多个换行合并为一个  
    .trim()                         // 去除首尾空白
}

// 提交作业批改
const handleSubmitGrading = async () => {
  if (!currentGradingAssignment.value?.id) {
    message.error('无法提交：缺少作业ID')
    return
  }
  
  if (!gradingResult.value) {
    message.error('无法提交：缺少批改结果')
    return
  }
  
  try {
    submitGradingLoading.value = true
    
    const res = await request.post('/studentAssignments/submitGrading', {
      id: currentGradingAssignment.value.id,
      gradingResult: gradingResult.value
    })
    
    if (res.code === 200) {
      message.success('批改结果已提交')
      gradingModalVisible.value = false
      fetchStudentAssignmentList()
    } else {
      message.error(res.message || '提交批改结果失败')
    }
  } catch (error) {
    console.error('提交批改结果失败', error)
    message.error('提交批改结果失败，请重试')
  } finally {
    submitGradingLoading.value = false
  }
}

// 重新批改
const handleReGrade = () => {
  if (!currentGradingAssignment.value?.id) {
    message.error('无法重新批改：缺少作业ID')
    return
  }
  
  // 重置状态并重新开始批改
  resetContentState()
  gradingResult.value = ''
  streamResponse.value = ''
  gradingLoading.value = true
  
  // 调用批改接口
  callGradingAPI(currentGradingAssignment.value.id)
}
</script>

<style lang="less" scoped>
.student-assignment-management {
  .table-page-search-wrapper {
    margin-bottom: 16px;
  }
  
  .ant-form-item {
    margin-bottom: 16px;
  }
  
  // 优化表格样式
  :deep(.ant-table-tbody > tr > td) {
    padding: 12px 16px;
  }
  
  // 提交按钮高亮
  :deep(.ant-btn-primary) {
    font-weight: 500;
  }
  
  // 批改作业对话框样式
  .ai-grading-modal {
    // 固定对话框高度
    :deep(.ant-modal-body) {
      height: 700px;
      overflow: hidden;
      padding: 20px;
    }
    
    .ai-grading-container {
      height: 100%;
      display: flex;
      flex-direction: column;
      
      .assignment-info {
        margin-bottom: 16px;
        flex-shrink: 0;
        
        :deep(.ant-descriptions-item-label) {
          font-weight: 600;
          background-color: #f8f9fa;
          width: 100px;
        }
      }
      
      .grading-content-wrapper {
        flex: 1;
        overflow-y: auto;
        padding-right: 8px;
        margin-bottom: 16px;
        
        // 自定义滚动条
        &::-webkit-scrollbar {
          width: 6px;
        }
        
        &::-webkit-scrollbar-track {
          background: #f1f1f1;
          border-radius: 3px;
        }
        
        &::-webkit-scrollbar-thumb {
          background: #c1c1c1;
          border-radius: 3px;
          
          &:hover {
            background: #a8a8a8;
          }
        }
        
        .thinking-section,
        .grading-section {
          margin-bottom: 16px;
          border-radius: 8px;
          overflow: hidden;
          transition: all 0.2s ease;
        }
        
        // DeepSeek风格思考区域
        .thinking-section {
          border: 1px solid #e2e8f0;
          background: linear-gradient(145deg, #f8fafc 0%, #f1f5f9 100%);
          
          .thinking-header-line {
            background: linear-gradient(145deg, #e2e8f0 0%, #cbd5e1 100%);
            padding: 12px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #d1d5db;
            
            .thinking-title-group {
              display: flex;
              align-items: center;
              
              .thinking-icon {
                margin-right: 8px;
                font-size: 16px;
                
                .ant-spin {
                  color: #6366f1;
                }
              }
              
              .thinking-text {
                font-weight: 500;
                color: #374151;
                font-size: 14px;
                margin-right: 12px;
              }
              
              .thinking-timer {
                color: #6b7280;
                font-size: 12px;
                background: rgba(255, 255, 255, 0.7);
                padding: 2px 8px;
                border-radius: 12px;
                font-weight: 500;
              }
            }
            
            .collapse-btn {
              color: #6366f1;
              font-size: 12px;
              padding: 0 4px;
              height: auto;
              
              &:hover {
                color: #4f46e5;
              }
            }
          }
          
          .thinking-content {
            background: rgba(248, 250, 252, 0.8);
            padding: 16px;
            
            &.thinking-active {
              animation: deepseek-thinking 2s infinite;
            }
            
            .thinking-text-content {
              position: relative;
              color: #6b7280;                    // 思考内容 - 更淡的灰色，突出对比
              font-size: 13px;                  // 稍小的字体
              line-height: 1.7;                 // 适中的行间距
              font-family: 'SF Mono', 'Monaco', 'Consolas', monospace;
              letter-spacing: 0.025em;          
              word-spacing: 0.12em;             
              font-weight: 400;                 // 正常字重，与批改结果的粗体形成对比
              white-space: pre-wrap;
              word-wrap: break-word;
              background: rgba(248, 250, 252, 0.7);  // 稍微加深背景
              padding: 14px 18px;               // 稍小的内边距
              margin: 8px 0;                    
              border-radius: 6px;               // 稍小的圆角
              border-left: 3px solid #cbd5e1;  // 更淡的边框色
              
              // 段落间距优化
              p, div {
                margin-bottom: 10px;            // 稍小的段落间距
                
                &:last-child {
                  margin-bottom: 0;
                }
              }
              
              .thinking-dots {
                color: #0277bd;
                font-weight: bold;
                margin-left: 8px;                
                
                span {
                  opacity: 0;
                  animation: thinking-dots 1.5s infinite;
                  margin-right: 2px;            
                  
                  &:nth-child(1) { animation-delay: 0s; }
                  &:nth-child(2) { animation-delay: 0.3s; }
                  &:nth-child(3) { animation-delay: 0.6s; }
                }
              }
            }
            
            .text-display {
              .grading-text-content {
                color: #0f172a;                    // 批改内容 - 深色调，更正式
                font-size: 15px;
                line-height: 1.9;                 // 更大的行间距
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                letter-spacing: 0.02em;           // 适中的字母间距
                word-spacing: 0.2em;              // 更大的单词间距
                white-space: pre-wrap;
                word-wrap: break-word;
                background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
                padding: 20px 24px;               // 更大的内边距
                margin: 12px 0;                   // 增加外边距
                border-radius: 10px;
                border-left: 4px solid #0277bd;
                box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
                
                // 优化文字间隙和段落
                text-align: left;                 // 改为左对齐，避免justify造成的不均匀间隙
                text-indent: 0;
                
                // 段落和句子间距
                p, div {
                  margin-bottom: 16px;
                  
                  &:last-child {
                    margin-bottom: 0;
                  }
                }
                
                // 特殊标点后的间距
                &::after {
                  content: '';
                  display: block;
                  height: 8px;
                }
                
                // 粗体强调样式 - 区分批改结果与思考过程
                &.grading-result-bold {
                  font-weight: 600;                // 粗体显示
                  color: #0a0a0a;                  // 更深的颜色
                  font-size: 16px;                 // 稍大的字体
                  line-height: 2.0;                // 更大的行间距
                  border-left: 5px solid #0277bd;  // 更粗的左边框
                  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.12);  // 更明显的阴影
                  
                  // 增强视觉层次
                  background: linear-gradient(145deg, #ffffff 0%, #f0f9ff 100%);
                  
                  // 强调重要内容
                  strong, b {
                    font-weight: 700;
                    color: #0277bd;
                  }
                  
                  // 流式显示效果
                  &.streaming {
                    border-left: 5px solid #06b6d4;  // 流式状态时用青色边框
                    background: linear-gradient(145deg, #ffffff 0%, #ecfdf5 100%);  // 淡绿色背景表示正在生成
                    position: relative;
                    
                    // 流式脉动效果
                    &::before {
                      content: '';
                      position: absolute;
                      top: 0;
                      left: -5px;
                      width: 5px;
                      height: 100%;
                      background: linear-gradient(
                        0deg,
                        #06b6d4 0%,
                        #22d3ee 50%,
                        #06b6d4 100%
                      );
                      animation: streaming-pulse 2s ease-in-out infinite;
                    }
                  }
                  
                  // 实时输入光标
                  .grading-cursor {
                    color: #0277bd;
                    font-weight: bold;
                    margin-left: 2px;
                    
                    span {
                      opacity: 1;
                      animation: cursor-blink 1s infinite;
                      font-size: 18px;
                      line-height: 1;
                    }
                  }
                }
              }
            }
          }
        }
        
        // 批改结果区域
        .grading-section {
          border: 1px solid #e0f2fe;
          background: linear-gradient(145deg, #f0f9ff 0%, #e0f7fa 100%);
          
          .grading-header-line {
            background: linear-gradient(145deg, #b3e5fc 0%, #81d4fa 100%);
            padding: 12px 16px;
            display: flex;
            align-items: center;
            border-bottom: 1px solid #4fc3f7;
            
            .grading-title-group {
              display: flex;
              align-items: center;
              
              .grading-icon {
                margin-right: 8px;
                font-size: 16px;
              }
              
              .grading-text {
                font-weight: 600;
                color: #0277bd;
                font-size: 14px;
              }
            }
          }
          
          .grading-content {
            background: rgba(255, 255, 255, 0.9);
            padding: 20px;
            
            .grading-loading-state {
              display: flex;
              flex-direction: column;
              align-items: center;
              justify-content: center;
              min-height: 200px;
              padding: 40px 20px;
              
              .loading-indicator {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 16px;
                
                p {
                  color: #64748b;
                  font-size: 14px;
                  font-weight: 500;
                  margin: 0;
                  letter-spacing: 0.02em;
                }
              }
            }
          }
        }
        
        .empty-state {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 200px;
          border: 2px dashed #d1d5db;
          border-radius: 8px;
          background: #f9fafb;
          
          .empty-icon {
            font-size: 48px;
            color: #9ca3af;
            margin-bottom: 12px;
          }
          
          :deep(.ant-empty-description) {
            color: #6b7280;
            font-size: 14px;
          }
        }
      }
      
      .grading-tips {
        flex-shrink: 0;
        
        :deep(.ant-alert) {
          border-radius: 6px;
          border: none;
          box-shadow: 0 1px 4px rgba(59, 130, 246, 0.15);
        }
      }
      
      .grading-actions {
        flex-shrink: 0;
        margin-top: 16px;
        padding: 16px 20px;
        background: linear-gradient(145deg, #f8fafc 0%, #f1f5f9 100%);
        border-radius: 8px;
        border: 1px solid #e2e8f0;
        text-align: center;
        
        :deep(.ant-btn) {
          font-weight: 500;
          border-radius: 6px;
          padding: 8px 24px;
          height: auto;
          
          &.ant-btn-primary {
            background: linear-gradient(135deg, #0277bd 0%, #0ea5e9 100%);
            border: none;
            box-shadow: 0 2px 8px rgba(2, 119, 189, 0.3);
            
            &:hover {
              background: linear-gradient(135deg, #01579b 0%, #0284c7 100%);
              transform: translateY(-1px);
              box-shadow: 0 4px 12px rgba(2, 119, 189, 0.4);
            }
            
            &:active {
              transform: translateY(0);
            }
          }
          
          &:not(.ant-btn-primary) {
            color: #0277bd;
            border-color: #0277bd;
            
            &:hover {
              color: #01579b;
              border-color: #01579b;
              background: rgba(2, 119, 189, 0.04);
            }
          }
        }
      }
    }
    
    // DeepSeek风格动画
    @keyframes deepseek-thinking {
      0%, 100% {
        background: rgba(248, 250, 252, 0.8);
      }
      50% {
        background: rgba(226, 232, 240, 0.6);
      }
    }
    
    @keyframes thinking-dots {
      0%, 20% { opacity: 0; }
      50% { opacity: 1; }
      100% { opacity: 0; }
    }
    
    // 流式显示动画
    @keyframes streaming-pulse {
      0% {
        background: linear-gradient(
          0deg,
          #06b6d4 0%,
          #22d3ee 50%,
          #06b6d4 100%
        );
      }
      50% {
        background: linear-gradient(
          0deg,
          #22d3ee 0%,
          #67e8f9 50%,
          #22d3ee 100%
        );
      }
      100% {
        background: linear-gradient(
          0deg,
          #06b6d4 0%,
          #22d3ee 50%,
          #06b6d4 100%
        );
      }
    }
    
    // 光标闪烁动画
    @keyframes cursor-blink {
      0%, 50% { opacity: 1; }
      51%, 100% { opacity: 0; }
    }
    
    @keyframes loading-fade {
      0%, 50% { opacity: 1; }
      75%, 100% { opacity: 0.6; }
    }
    
    // 响应式适配
    @media (max-width: 768px) {
      :deep(.ant-modal-body) {
        height: 600px;
        padding: 16px;
      }
      
      .ai-grading-container {
        .thinking-section,
        .grading-section {
          .thinking-header-line,
          .grading-header-line {
            padding: 10px 14px;
            
            .thinking-title-group,
            .grading-title-group {
              .thinking-text,
              .grading-text {
                font-size: 13px;
              }
              
              .thinking-timer {
                font-size: 11px;
              }
            }
          }
          
          .thinking-content,
          .grading-content {
            padding: 14px;
            
            .thinking-text-content,
            .text-display {
              font-size: 12px;
              line-height: 1.5;
            }
          }
        }
      }
    }
  }
}
</style> 